package ui.activity.home;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Html;
import android.text.Spanned;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.jakewharton.rxbinding.view.RxView;
import com.jakewharton.rxbinding.widget.RxTextView;
import com.jakewharton.rxbinding.widget.TextViewAfterTextChangeEvent;

import net.ck.hzq.R;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import Bean.ProductBean;
import Utils.StringUtil;
import base.BaseAct;
import butterknife.BindView;
import cn.finalteam.loadingviewfinal.OnDefaultRefreshListener;
import cn.finalteam.loadingviewfinal.PtrClassicFrameLayout;
import cn.finalteam.loadingviewfinal.PtrFrameLayout;
import cn.finalteam.loadingviewfinal.ScrollViewFinal;
import coom.Constants;
import event.NetErrorEvent;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import ui.activity.home.biz.NewProductBiz;
import ui.activity.home.component.DaggerNewProductComponent;
import ui.activity.home.contract.NewProductContract;
import ui.activity.home.module.NewProductModule;
import ui.activity.home.presenter.NewProductPresenter;
import ui.activity.order.ConfirmOrderAct;
import util.HtmlTagHandler;
import util.StringUtils;

/**
 * 商品详情
 */
public class NewProductAct extends BaseAct implements NewProductContract.View {


    @Inject
    NewProductPresenter presenter;
    @Inject
    NewProductBiz biz;

    @BindView(R.id.product_image)
    SimpleDraweeView productImage;
    @BindView(R.id.product_price)
    TextView productPrice;
    @BindView(R.id.product_time)
    TextView productTime;
    @BindView(R.id.kuaidifei)
    TextView kuaidifei;

    @BindView(R.id.product_describe1)
    TextView productDescribe1;
    @BindView(R.id.product_describe2)
    TextView productDescribe2;
    @BindView(R.id.product_describe3)
    TextView productDescribe3;
    @BindView(R.id.product_describe4)
    TextView productDescribe4;
    @BindView(R.id.product_name)
    TextView productName;
    @BindView(R.id.product_money)
    TextView productMoney;
    @BindView(R.id.product_money_describe)
    TextView productMoneyDescribe;
    @BindView(R.id.product_subtract)
    Button productSubtract;
    @BindView(R.id.product_number)
    EditText productNumber;
    @BindView(R.id.product_addition)
    Button productAddition;
    @BindView(R.id.sv)
    ScrollViewFinal sv;
    @BindView(R.id.ptr_layout)
    PtrClassicFrameLayout ptr;
    @BindView(R.id.product_bottom_layout)
    LinearLayout bottomLayout;
    @BindView(R.id.product_order)
    Button order;
    @BindView(R.id.product_submit)
    Button submit;


    private String id;
    ProductBean.DataBean.ItemBean itemBean;

    @Override
    protected void setRoot() {
//        setTitleBar(R.color.colorBlue);
        setContentView(R.layout.activity_product_new);
    }

    @Override
    protected void setup() {
        DaggerNewProductComponent.builder().newProductModule(new NewProductModule(this)).build().inject(this);
        setToolBar(getResources().getString(R.string.lang_product), "");
        presenter.setBiz(biz);
    }

    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        Constants.activitys.clear();
        Constants.activitys.add(this);
        id = StringUtil.isNullOrEmpty(getIntent().getStringExtra(Constants.KEYSTRING)) ? "0" : getIntent().getStringExtra(Constants.KEYSTRING);
        sv.setOnLoadMoreListener(() -> {
        });
        ptr.setOnRefreshListener(new OnDefaultRefreshListener() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                presenter.getPosModel(true, id);
            }
        });
        ptr.autoRefresh(true);
        RxView.clicks(order)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(Void -> presenter.toOrder());
        RxView.clicks(submit)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(Void -> presenter.toSubmitOrder());
        RxView.clicks(productSubtract)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(Void -> presenter.toNumber(0));
        RxView.clicks(productAddition)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(Void -> presenter.toNumber(1));
        RxTextView.afterTextChangeEvents(productNumber)
                .compose(this.<TextViewAfterTextChangeEvent>bindToLifecycle())
                .debounce(250, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<TextViewAfterTextChangeEvent>() {
                    @Override
                    public void call(TextViewAfterTextChangeEvent event) {
                        String temp = event.editable().toString();
                        presenter.toInput(temp);
                    }
                });
    }

    @Override
    public void onNetErrorEvent(NetErrorEvent event) {
        super.onNetErrorEvent(event);
    }

    @Override
    protected void onNetError(NetErrorEvent event) {
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        biz.onDestory();
    }

    @Override
    public void loadMoreComplete() {
        sv.onLoadMoreComplete();
    }

    @Override
    public void hasLoadMore(boolean b) {
        sv.setHasLoadMore(false);
    }

    @Override
    public void refreshComplete() {
        ptr.onRefreshComplete();
    }

    @Override
    public void upDateUI(ProductBean.DataBean bean) {
        itemBean = bean.getItem();
        productImage.setImageURI(Uri.parse(bean.getItem().getSellImgPath()));
        String priceInfo = "¥ <myfont color=#FFFFFF size='48px' >" + StringUtil.getFormatPrice(itemBean.getPrice()) + "</myfont>/" + itemBean.getNumber() + "台";
        Spanned priceStr = Html.fromHtml(priceInfo, null, new HtmlTagHandler("myfont"));
        productPrice.setText(priceStr);
        kuaidifei.setText("快递费：¥" + bean.getItem().getExpressCost() + "元");
        String dayStr = "";
        String dayStringInfo = "";
        if (bean.getRules().size() > 0) {
            dayStringInfo = "（有效期" + bean.getRules().get(0).getExpireTime() + "天）";
            for (int i = 0; i < bean.getRules().size(); i++) {
                dayStr = dayStr + bean.getRules().get(i).getExpireTime() + "/";
            }
            if (dayStr.length() > 1) {
                dayStr = dayStr.substring(0, dayStr.length() - 1);
            }
        } else {
            dayStringInfo = "（有效期" + itemBean.getUntilDay() + "天）";
            dayStr = itemBean.getUntilDay();
        }
        productTime.setText(itemBean.getActTimeDesc());
        String describe1Info = itemBean.getName() + "<font color=#5A5E66 >" + itemBean.getSellName() + "</font>";
        Spanned describe1Str = Html.fromHtml(describe1Info);
        productDescribe1.setText(describe1Str);
        if (itemBean.getCategoryId().equals("4")) {
            productDescribe2.setText(itemBean.getActDescription());
            productDescribe2.setTextColor(Color.parseColor("#00A0E9"));
            productDescribe3.setText("返代理商" + bean.getItem().getReturnAmount() + "元/台");
            productDescribe3.setTextColor(Color.parseColor("#00A0E9"));
            productDescribe4.setVisibility(View.GONE);
        } else if (itemBean.getCategoryId().equals("3")) {
//            String describe2Info = "单次采购<font color=#FF4040  >发货" + itemBean.getSingleShipPurchase() + "</font>，激活" + itemBean.getAfterActivation() + "后发余货";
//            Spanned describe2Str = Html.fromHtml(describe2Info);
//            productDescribe2.setText(describe2Str);
            productDescribe3.setText(itemBean.getFreezeDesc());
            productDescribe2.setVisibility(View.GONE);
            String describe4Info = itemBean.getBackDesc() + (StringUtils.isEmpty(itemBean.getActiveDesc()) ? "" : "（<font color=#FF4040 >" + itemBean.getActiveDesc() + "</font>)");
            Spanned describe4Str = Html.fromHtml(describe4Info);
            productDescribe4.setText(describe4Str);
        } else if (itemBean.getCategoryId().equals("2")) {
            productDescribe2.setText(itemBean.getDescription());
            productDescribe3.setText(itemBean.getFreezeDesc());
            productDescribe3.setTextColor(Color.parseColor("#00A0E9"));
            productDescribe4.setText(itemBean.getActiveDesc());
            productDescribe4.setTextColor(Color.parseColor("#FF4040"));
        } else if (itemBean.getCategoryId().equals("9")) {
            productDescribe3.setText(itemBean.getFreezeDesc());
            productDescribe2.setVisibility(View.GONE);
            String describe4Info = itemBean.getBackDesc() + (StringUtils.isEmpty(itemBean.getActiveDesc()) ? "" : "（<font color=#FF4040 >" + itemBean.getActiveDesc() + "</font>)");
            Spanned describe4Str = Html.fromHtml(describe4Info);
            productDescribe4.setText(describe4Str);
        } else {
            productDescribe3.setText(itemBean.getFreezeDesc());
            productDescribe2.setVisibility(View.GONE);
            String describe4Info = itemBean.getBackDesc() + (StringUtils.isEmpty(itemBean.getActiveDesc()) ? "" : "（<font color=#FF4040 >" + itemBean.getActiveDesc() + "</font>)");
            Spanned describe4Str = Html.fromHtml(describe4Info);
        }
        productName.setText(itemBean.getName());
        productMoney.setText(StringUtil.getFormatPrice(itemBean.getPrice()));
        productMoneyDescribe.setText(dayStringInfo);
        sv.setVisibility(View.VISIBLE);
        bottomLayout.setVisibility(View.VISIBLE);
    }

    @Override
    public void submitOrder(int buyNumber, String price) {
        if (itemBean == null) {
            showMsg("数据错误，请刷新页面");
            return;
        }
        Intent intent = new Intent(NewProductAct.this, ConfirmOrderAct.class);
        intent.putExtra("id", itemBean.getId());
        intent.putExtra("pic", itemBean.getImgPath());
        intent.putExtra("type", 1);//货物类型 1 pos 2 物料
        intent.putExtra("sellName", itemBean.getSellName());
        intent.putExtra("buyNumber", buyNumber + "");
        intent.putExtra("price", StringUtil.getFormatPrice(itemBean.getPrice()));
        intent.putExtra("totalPrice", price);
        startActivity(intent);
    }

    @Override
    public void updatePrice(int number, String price, String priceType) {
        if (productNumber.getText().toString().equals("0")) {
            productNumber.setText("1");
            productNumber.setSelection(productNumber.getText().toString().length());
        }
        if (number <= 1) {
            productSubtract.setBackgroundResource(R.mipmap.subtract);
        } else {
            productSubtract.setBackgroundResource(R.mipmap.subtract_drak);
        }
        productMoney.setText("¥" + price);
        productMoneyDescribe.setText(priceType);
    }

    @Override
    public void upDateNumber(int number) {
        productNumber.setText(number + "");
    }
}

